import { DatePicker, Form, Button, message } from 'antd';
import { useRequest } from 'ahooks';
import { getAnalysis_graph } from '@/api/sr-stms';
import Chart from './src/chart';
import moment from 'moment';
import { useEffect } from 'react';

const { RangePicker } = DatePicker;

interface ContentProps {
  cam_no?: string;
}

const Content = (props: ContentProps) => {
  const { cam_no } = props;
  const [form] = Form.useForm();
  const { data, run, loading } = useRequest(
    ({ start_time, end_time, ai_type }) =>
      getAnalysis_graph({ start_time, end_time, ai_type }),
    {
      manual: true,
      formatResult: (res) =>
        res.data?.map((item: any) => ({ ...item, type: 'line' })),
      onSuccess: (data) => {
        if (data.length === 0) {
          message.success('当前时间区间没有数据！');
        }
      },
    },
  );

  const formatTime = (time: [moment.Moment, moment.Moment]) => {
    return {
      start_time: moment(time[0]).format('YYYY-MM-DD HH:mm:ss'),
      end_time: moment(time[1]).format('YYYY-MM-DD HH:mm:ss'),
    };
  };

  const onFinish = (vals: any) => {
    const timeObj = formatTime(vals);
    if (cam_no) {
      run({ ...timeObj, ai_type: cam_no });
    }
  };

  useEffect(() => {
    if (cam_no) {
      form.validateFields().then((vals) => {
        const timeObj = formatTime(vals);
        run({ ...timeObj, ai_type: cam_no });
      });
    }
  }, [cam_no]);

  return (
    <div>
      <Form
        form={form}
        layout="inline"
        onFinish={onFinish}
        style={{ marginBottom: 30 }}
      >
        <Form.Item
          name="time"
          label="时间区间"
          rules={[{ required: true, message: '请选择时间区间' }]}
        >
          <RangePicker showTime></RangePicker>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            绘制
          </Button>
        </Form.Item>
      </Form>

      <Chart series={data} loading={loading}></Chart>
    </div>
  );
};

export default Content;
